package com.bluedot.controller;

import com.alibaba.fastjson.JSON;
import com.bluedot.pojo.pack.PreMappedStatement;
import com.bluedot.pojo.pack.ResultEntity;
import com.bluedot.pojo.po.Log;
import com.bluedot.pojo.vo.UserVO;
import com.bluedot.service.UtilTool;
import jdk.internal.util.xml.impl.Input;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "UploadServlet",urlPatterns = "/up/*")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        InputStream file = req.getPart("file").getInputStream();
//        InputStream file=null;
        // 1. 获取路由信息
        StringBuffer url = req.getRequestURL();
        PreMappedStatement<String> statement = new PreMappedStatement<>(url.toString(), file, req);
        // 4. 添加到请求队列中去
        ResultEntity  resultEntity = logInsert(statement, req);
        // 5. 设置响应包
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(JSON.toJSONString(resultEntity));
        resp.getWriter().flush();
    }



    /**
     * <p>描述:日志插入方法 <p>
     *
     * @param
     * @return
     * @author QiYu
     * @CreateDate 2022/9/7 11:00
     * @update [序号][日期YYYY-MM-DD][王震宇][变更描述]
     */
    private ResultEntity logInsert(PreMappedStatement preMappedStatement, HttpServletRequest req) {

        ResultEntity re = null;
        UtilTool utilTool = new UtilTool();

        String[] split = (preMappedStatement.getMethodType().split("/"));
        String s = split[split.length - 1];

//      凡是不是查询的一律插入日志，以及特殊接口getInfo
        if (!s.contains("query")&&!"getInfo".equals(s)) {
            //获取ip地址
            String ipv4 = req.getRemoteAddr();
            //将本机localhost改为127.0.0.1
            if ("0:0:0:0:0:0:0:1".equals(ipv4))ipv4 = "127.0.0.1";
//          获取请求路径
            String requestURI = req.getRequestURI();
//          获取sessionUser可能为空
            UserVO user = (UserVO)req.getSession().getAttribute("user");
//          创建log对象
            Log log = new Log();
            log.setLogUrl(requestURI);
            log.setHanderIp(ipv4);
            try {
                re = MessageQueue.addQueue(preMappedStatement);
            } catch (Exception e) {
//              将操作失败日志插入数据库,注意登录的时候报异常的话，不能加入到日志；
//              获取用户的id，这里判断非空因为登录失败没有存储session，所以要判断
                if (user!=null)log.setHanderId(user.getUserId());
//              设置日志状态为0
                log.setLogState(0);
//               登录的时候报异常不能加入到日志
                if (!s.contains("login")) utilTool.insert(new PreMappedStatement(UtilTool.INSERT, log));
                throw new RuntimeException(e);
            }
//          将没有异常的日志加入到日志
//          日志状态失败还是成功与否来设置日志状态
            if ("FALSE".equals(re.getResult())) log.setLogState(0);
            else log.setLogState(1);
//          获取用户id，用户不能为空；防止登录失败导致空指针异常
            if (user!=null) {
                log.setHanderId(user.getUserId());
                utilTool.insert(new PreMappedStatement(UtilTool.INSERT, log));
            }

            return re;
        }
//      不用插入日志
        try {
            return MessageQueue.addQueue(preMappedStatement);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}